/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.myapp.struts.action;

import com.myapp.hibernate.model.Usuario;
import com.myapp.hibernate.util.UsuarioUtil;
import com.myapp.struts.form.LoginForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

/**
 *
 * @author aacede
 */
public class LoginAction extends org.apache.struts.action.Action {

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";
    private static final String INIT = "init";

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        LoginForm formulario = (LoginForm) form;
        UsuarioUtil usuarioUtil = new UsuarioUtil();
        Usuario usuarioLogado = null;
        try {
            usuarioLogado = usuarioUtil.obtenerUsuarioLogin(formulario.getEmail(), formulario.getPass());
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        if (usuarioLogado != null) {
            request.getSession().setAttribute("UsuarioLogado", usuarioLogado);
            return mapping.findForward(SUCCESS);
        } else {
            ActionErrors errors = new ActionErrors();
            errors.add("noUsuario", new ActionMessage("error.noUsuario"));
            saveErrors(request, errors);
            return mapping.findForward(INIT);
        }

    }
}
